package com.learn.image.service.impl;

import org.springframework.stereotype.Service;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.nio.file.Files;
import java.nio.file.Paths;

import static com.learn.image.constant.Constant.FONT;
import static com.learn.image.constant.Constant.WATER_COLOR;
import static jdk.nashorn.internal.runtime.regexp.joni.encoding.CharacterType.ALPHA;

/**
 * @description: TODO
 * @author: Administrator
 * @createTime: 2023/11/29 0029 15:26
 * @version: 1.0
 */
@Service
public class ImageWatermarkService {

    /**
     * imgFile 图像文件
     * imageFileName 图像文件名
     * uploadPath 服务器上上传文件的相对路径
     * realUploadPath 服务器上上传文件的物理路径
     */
    public String watermarkAdd(File imgFile, String imageFileName, String uploadPath, String realUploadPath) {

        String imgWithWatermarkFileName = "watermark_" + imageFileName;
        OutputStream os = null;

        try {
            // 源图片
            Image image = ImageIO.read(imgFile);

            int width = image.getWidth(null);
            int height = image.getHeight(null);

            BufferedImage bufferedImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);  // ①
            // 得到画笔对象
            Graphics2D g = bufferedImage.createGraphics();  // ②
            g.drawImage(image, 0, 0, width, height, null);  // ③

            String logoPath = realUploadPath + "/" + "/img-folder/20231129101118.png";  // 水印图片地址
            File logo = new File(logoPath);        // 读取水印图片
            Image imageLogo = ImageIO.read(logo);

            int markWidth = imageLogo.getWidth(null);    // 水印图片的宽度和高度
            int markHeight = imageLogo.getHeight(null);

            g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_ATOP, ALPHA));  // 设置水印透明度
            g.rotate(Math.toRadians(-10), bufferedImage.getWidth() / 2, bufferedImage.getHeight() / 2);  // 设置水印图片的旋转度


            //添加单个水印
            double x2 = width * 0.9 - markWidth;
            double y2 = height * 0.9 - markHeight;
            g.drawImage(imageLogo, new Double(x2).intValue(), new Double(y2).intValue(), null);  // ④

          /*  // 循环添加多个水印logo
          double count = 1.5;
            while ( x < width*count ) {  // 循环添加多个水印logo
                y = -height / 2;
                while( y < height*count ) {
                    g.drawImage(imageLogo, x, y, null);  // ④
                    y += markHeight + yInterval;
                }
                x += markWidth + xInterval;
            }*/

            g.dispose();

            os = Files.newOutputStream(Paths.get(realUploadPath + "/" + imgWithWatermarkFileName));
//            JPEGImageEncoder en = JPEGCodec.createJPEGEncoder(os); // ⑤
//            en.encode(bufferedImage); // ⑥
            writeImageToJPEG(bufferedImage,imgWithWatermarkFileName,0.86f);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (os != null) {
                try {
                    os.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

        return uploadPath + "/" + imgWithWatermarkFileName;
    }

    public static void writeImageToJPEG(BufferedImage image, String filePath, float quality) throws IOException {
        File outputFile = new File(filePath);
        ImageIO.write(image, "jpeg", outputFile); // 使用 "jpeg" 表示写入 JPEG 格式
    }
    /**
     * 给图片添加水印文字
     *
     * @param text       水印文字
     * @param srcImgPath 源图片路径
     * @param targetPath 目标图片路径
     */
    public String markImage(String text, String srcImgPath, String targetPath, String uploadPath) {
        return markImage(text, srcImgPath, targetPath, uploadPath, null);
    }


    /**
     * 给图片添加水印文字、可设置水印文字的旋转角度
     *
     * @param text
     * @param srcImgPath
     * @param targetPath
     * @param degree
     */
    public String markImage(String text, String srcImgPath, String targetPath, String uploadPath, Integer degree) {

        targetPath = targetPath + "watermark.jpg";

        OutputStream os = null;
        try {
            // 0、图片类型
            String type = srcImgPath.substring(srcImgPath.indexOf(".") + 1, srcImgPath.length());

            // 1、源图片
            Image srcImg = ImageIO.read(new File(srcImgPath));

            int imgWidth = srcImg.getWidth(null);
            int imgHeight = srcImg.getHeight(null);

            BufferedImage buffImg = new BufferedImage(imgWidth, imgHeight, BufferedImage.TYPE_INT_RGB);

            // 2、得到画笔对象
            Graphics2D g = buffImg.createGraphics();
            // 3、设置对线段的锯齿状边缘处理
            g.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);
            g.drawImage(srcImg.getScaledInstance(imgWidth, imgHeight, Image.SCALE_SMOOTH), 0, 0, null);
            // 4、设置水印旋转
            if (null != degree) {
                g.rotate(Math.toRadians(degree), (double) buffImg.getWidth() / 2, (double) buffImg.getHeight() / 2);
            }
            // 5、设置水印文字颜色
            g.setColor(WATER_COLOR);
            // 6、设置水印文字Font
            g.setFont(FONT);
            // 7、设置水印文字透明度
            g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_ATOP, ALPHA));
            // 8、第一参数->设置的内容，后面两个参数->文字在图片上的坐标位置(x,y)
            int positionWidth = 50;
            int positionHeight = imgHeight - 30;
            g.drawString(text, positionWidth, positionHeight);
            // 9、释放资源
            g.dispose();
            // 10、生成图片
            os = Files.newOutputStream(Paths.get(targetPath));
            // ImageIO.write(buffImg, "JPG", os);
            ImageIO.write(buffImg, type.toUpperCase(), os);

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (null != os) {
                    os.close();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        return uploadPath + "/" + "watermark.jpg";
    }


}
